<template>
  <el-space v-if="data" alignment="flex-start" direction="horizontal" wrap>
    <el-space direction="vertical">
      <div v-for="(val, key, index) in mapValue">
        <p>{{ key }}</p>
        <el-select
            v-model="mapValue[key]['GraphType']"
            placeholder="Select"
            style="width: 240px"
        >
          <el-option
              v-for="item in mapType"
              :key="item"
              :label="item"
              :value="item"
              :disabled="mapValue[key]['GraphType'] == 'none'"
          />
        </el-select>
      </div>
    </el-space>
    <div class="m-4" v-for="(val, key, index) in mapValue">
      <el-space direction="vertical" v-if="mapValue[key]['GraphType'] === 'bar'">
        <CcvSimpleBarChart
            v-if="mapValue[key]['GraphType'] === 'bar' && mapValue[key]['GraphData']?.length"
            :data="mapValue[key]['GraphData']"
            :options="barOptions(key)"
        />
        <el-input
            v-model="mapValue[key]['GraphSegment']"
            @change="segmentChange(key)"
        />
      </el-space>
      <CcvPieChart
          v-if="mapValue[key]['GraphType'] === 'pie' && mapValue[key]['GraphData']?.length"
          :data="mapValue[key]['GraphData']"
          :options="pieOptions(key)"
      />
      <CcvLineChart
          v-if="mapValue[key]['GraphType'] === 'line' && mapValue[key]['GraphData']?.length"
          :data="mapValue[key]['GraphData']"
          :options="lineOptions(key)"
      />
    </div>
  </el-space>
</template>

<script setup lang="ts">
import { type ModelRef, type Ref, ref, watch } from "vue";
// 假设引入了CcvLineChart组件
// import CcvLineChart from "@/components/CcvLineChart.vue";
// import { defineModel } from "@/utils/defineModel";

const data: ModelRef<Array<any> | undefined> = defineModel();
const mapType = ["pie", "bar","line" ,"close"];
let mapValue: Ref<any> = ref({});
let defaultSegments = {
  // 单独分区
  "Year_Birth": "0,1900,1930,1960,1990",
  "Income": "0,10000,20000,30000,40000,50000,60000,70000"
};

function isNumeric(value: string) {
  return!isNaN(parseFloat(value)) &&!isNaN(value);
}

function getMapValue() {
  mapValue.value = {};
  if (data.value) {
    for (let key in data.value[0]) {
      mapValue.value[key] = {};
      if (isNumeric(data.value[0][key])) {
        mapValue.value[key] = setGraph(key, defaultSegments[key]);
      } else if (typeof data.value[0][key] === "string") {
        mapValue.value[key] = setGraph(key);
      } else if (typeof data.value[0][key] === "boolean") {
        mapValue.value[key] = setGraph(key);
      }
    }
  }
}

getMapValue();

watch(data, () => {
  console.log("data changed");
  getMapValue();
}, { deep: true, immediate: true });

function setGraph(
    attribute: string,
    inputSegment?: string
): { GraphType: string; GraphData: any[] } {
  if (inputSegment) {
    // 处理数值类型数据，生成柱状图或折线图的数据
    let cluster = [];
    let segments = inputSegment.split(",");
    for (let i = 0; i < segments.length; i++) {
      if (i == segments.length - 1) {
        cluster.push({ group: `${segments[i]}+`, value: 0 });
      } else {
        cluster.push({ group: `${segments[i]}-${segments[i + 1]}`, value: 0 });
      }
    }

    if (data.value) {
      for (const star of data.value) {
        for (let i = 0; i < segments.length; i++) {
          if (
              i < segments.length - 1 &&
              star[attribute] >= Number(segments[i]) &&
              star[attribute] < Number(segments[i + 1])
          ) {
            cluster[i].value += 1;
            break;
          }
          if (i == segments.length - 1) {
            cluster[i].value += 1;
            break;
          }
        }
      }
    }
    return {
      GraphType: "bar",
      GraphData: cluster
    };
  } else {
    // 处理字符串或布尔类型数据，生成饼图的数据
    let cluster = [];
    if (data.value) {
      for (const star of data.value) {
        let starAttribute = "";
        if (star[attribute] === undefined || star[attribute] === null) {
          starAttribute = "null";
        } else {
          starAttribute = star[attribute]?.toString();
        }
        if (cluster.length == 0) {
          cluster.push({ group: starAttribute, value: 1 });
          continue;
        }
        for (let clusterObject of cluster) {
          if (clusterObject.group == starAttribute) {
            clusterObject.value += 1;
            break;
          }
          if (clusterObject == cluster[cluster.length - 1]) {
            cluster.push({ group: starAttribute, value: 1 });
          }
        }
        if (cluster.length > 50) {
          return {
            GraphType: "none",
            GraphData: []
          };
        }
      }
    }
    return {
      GraphType: "pie",
      GraphData: cluster
    };
  }
}

function segmentChange(key) {
  mapValue.value[key] = setGraph(key, mapValue.value[key]["GraphSegment"]);
}

let pieOptions = (title: string) => {
  return {
    title: title,
    resizable: true,
    height: "400px",
    width: "400px",
    legend: {
      alignment: "center"
    },
    pie: {
      alignment: "center"
    }
  };
};

let barOptions = (title: string) => {
  return {
    title: title,
    height: "400px",
    width: "400px",
    axes: {
      left: {
        mapsTo: "value"
      },
      bottom: {
        mapsTo: "group",
        scaleType: "labels"
      }
    },
    accessibility: {
      svgAriaLabel: "Simple bar chart"
    }
  };
};



let lineOptions = (title: string) => {
  return {
    title: title,
    height: "400px",
    width: "400px",
    axes: {
      left: {
        mapsTo: "value"
      },
      bottom: {
        mapsTo: "group",
        scaleType: "labels"
      }
    },
    line: {
      connectNulls: true
    },
    accessibility: {
      svgAriaLabel: "Simple line chart"
    }
  };
};
</script>

<style scoped></style>